import os
import yaml
from typing import Dict, Any, Optional

class Config:
    """配置工具类"""
    
    _instance: Optional['Config'] = None
    
    def __new__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self, config_path: Optional[str] = None):
        if not hasattr(self, 'initialized'):
            self.config_path = config_path or os.path.join(
                os.path.dirname(os.path.dirname(__file__)),
                'config',
                'default.yaml'
            )
            self.config: Dict[str, Any] = {}
            self.load_config()
            self.initialized = True
    
    def load_config(self) -> None:
        """加载配置文件"""
        try:
            with open(self.config_path, 'r', encoding='utf-8') as f:
                self.config = yaml.safe_load(f)
        except Exception as e:
            raise RuntimeError(f"Failed to load config file: {e}")
    
    def get(self, key: str, default: Any = None) -> Any:
        """获取配置项"""
        keys = key.split('.')
        value = self.config
        for k in keys:
            if isinstance(value, dict):
                value = value.get(k, default)
            else:
                return default
        return value
    
    def set(self, key: str, value: Any) -> None:
        """设置配置项"""
        keys = key.split('.')
        config = self.config
        for k in keys[:-1]:
            if k not in config:
                config[k] = {}
            config = config[k]
        config[keys[-1]] = value
    
    def save(self) -> None:
        """保存配置到文件"""
        try:
            with open(self.config_path, 'w', encoding='utf-8') as f:
                yaml.safe_dump(self.config, f, allow_unicode=True)
        except Exception as e:
            raise RuntimeError(f"Failed to save config file: {e}")
    
    def update(self, new_config: Dict[str, Any]) -> None:
        """更新配置"""
        self.config.update(new_config) 